#pragma once

#include "Util.hpp"
#include <mutex>
#include <unordered_map>

class online_manager 
{
public:

    // 进入游戏大厅
    void enter_game_hall(uint32_t uid, webserver_t::connection_ptr& conn)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _hall_user.insert({uid, conn});
    }

    // 进入游戏房间
    void enter_game_room(uint32_t uid, webserver_t::connection_ptr& conn)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _room_user.insert({uid, conn});
    }

    // 退出游戏大厅
    void exit_game_hall(uint32_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _hall_user.erase(uid);
    }
    // 退出游戏房间
    void exit_game_room(uint32_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _room_user.erase(uid);
    }

    // 在游戏大厅中
    bool in_game_hall(uint32_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _hall_user.find(uid);
        if (it == _hall_user.end())
        {
            return false;
        }
        else 
        {
            return true;
        }
    }
    // 在游戏房间中
    bool in_game_room(uint32_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _room_user.find(uid);
        if (it == _room_user.end())
        {
            return false;
        }
        else 
        {
            return true;
        }
    }

    // 通过用户ID获取其游戏大厅的通信连接
    webserver_t::connection_ptr get_hall_con_from_uid(uint32_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _hall_user.find(uid);
        if (it == _hall_user.end())
        {
            return webserver_t::connection_ptr(nullptr);
        }
        else 
        {
            return it->second;
        }
    }
    // 通过用户ID获取其游戏房间的通信连接
    webserver_t::connection_ptr get_room_con_from_uid(uint32_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _room_user.find(uid);
        if (it == _room_user.end())
        {
            return webserver_t::connection_ptr(nullptr);
        }
        else 
        {
            return it->second;
        }
    }

    std::pair<std::unordered_map<uint32_t, webserver_t::connection_ptr>::const_iterator, std::unordered_map<uint32_t, webserver_t::connection_ptr>::const_iterator>
    get_users_from_room()
    {
        return {_room_user.begin(), _room_user.end()};
    }


private:
    std::mutex _mutex;
    //用于建立游戏大厅与用户ID的关联
    std::unordered_map<uint32_t, webserver_t::connection_ptr> _hall_user;
    //用于建立游戏房间与用户ID的关联
    std::unordered_map<uint32_t, webserver_t::connection_ptr> _room_user;
};